package com.atguigu.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.base.BaseDao;
import com.atguigu.base.BaseServiceImpl;
import com.atguigu.dao.DictDao;
import com.atguigu.entity.Dict;
import com.atguigu.service.DictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 杨林
 * @create 2022-09-17 9:50 星期六
 * description:
 */
@Service(interfaceClass = DictService.class)
@Transactional
public class DictServiceImpl extends BaseServiceImpl<Dict> implements DictService {

    @Autowired
    private DictDao dictDao;

    @Override
    protected BaseDao<Dict> getEntityDao() {
        return dictDao;
    }

    @Override
    public List<Map<String, Object>> findZnodes(Long id) {
        //根据id获取子节点数据
        //通过循环转换为指定的Json格式（其中要判断该节点是否是父节点）

       //zTree中的数据格式
        /*
        [
            { id:'031', name:'n3.n1', isParent:true},
            { id:'032', name:'n3.n2', isParent:false},
            { id:'033', name:'n3.n3', isParent:true},
            { id:'034', name:'n3.n4', isParent:false}
         ]
         */


        //根据id获取子节点数据列表
        List<Dict> dictList = dictDao.findZnodes(id);

        //构建zTree数据
        List<Map<String,Object>> zNodes = new ArrayList<>();

        for (Dict dict : dictList) {
            Map<String,Object> map = new HashMap<>();
            Integer count = dictDao.countIsParent(dict.getId());
            map.put("id",dict.getId());
            map.put("isParent", count > 0 ? true : false);
            map.put("name",dict.getName());

            zNodes.add(map);
        }
        return zNodes;
    }



    @Override
    public List<Dict> findListByParentId(Long parentId) {
        //根据id获取子节点数据列表
        List<Dict> dictList = dictDao.findZnodes(parentId);
        return dictList;
    }

    @Override
    public String getNameById(Long dictId) {
        return dictDao.getNameById(dictId);
    }

    @Override
    public List<Dict> findListByDictCode(String dictCode) {
        //根据dictCode获取id
        Dict dict = dictDao.getByDictCode(dictCode);
        if (dict == null){
            return null;
        }

        //根据id作为parentId 查询下级列表
        List<Dict> dictList = dictDao.findZnodes(dict.getId());
        return dictList;
    }

}
